<?php

declare(strict_types=1);

namespace app\controller\sys;

use think\facade\Config;
use think\file\UploadedFile;
use think\exception\ValidateException;

use app\utils\ReUtils;
use app\utils\FileUtils;
use think\facade\Env;

/**
 * upload文件管理
 *
 * @version      0.0.0
 * @author      by huwhois
 * @time        2017/11/27
 */
class FileManager extends Base
{
    protected $modelName = 'FileManager';

    public function uploadImage()
    {
        if ($this->app->request->isPost()) {
            $file = $this->request->file('upload_file');
            if ($file) {
                try {
                    validate(
                        [
                            'file' => [
                                // 限制文件大小(单位b)，这里限制为4M
                                'fileSize' => 4 * 1024 * 1024,
                                // 限制文件后缀，多个后缀以英文逗号分割
                                'fileExt'  => 'jpg,png,gif,jpeg,webp,jfif'
                            ]
                        ],
                        [
                            'file.fileSize' => '文件太大',
                            'file.fileExt' => '不支持的文件后缀',
                        ]
                    )->check(['file' => $file]);
                    
                    $picture_url = Config::get('filesystem.disks.public.url') . '/';
                    
                    $watermark = $this->request->has('watermark') ? intval($this->request->param('watermark')) : 0;

                    if ($watermark == 0) {
                        $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
                    } else {
                        $source = str_replace("\\", '/', $this->app->getRootPath() . Env::get('watermark', 'public/static/images/watermark.png'));
    
                        if (!is_file($source)) {
                            $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
                        } else {
                            $savename = $file->hashName();
    
                            $savepath = str_replace("\\", '/', Config::get('filesystem.disks.public.root') . DIRECTORY_SEPARATOR . $savename);
    
                            $dir = dirname($savepath);
    
                            if (!is_dir($dir)) {
                                mkdir($dir, 0755, true);
                            }
    
                            $image = \think\Image::open($file);
                            
                            $image->water($source);
    
                            $image->save($savepath);
                            
                            $image = null;
                        }
                    }

                    return ReUtils::result([
                        'filename' => $picture_url . str_replace("\\", '/', $savename)
                    ], 0, '上传成功');
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }
        }
    }

    /**
     * 网络图片上传
     */
    public function uploadUrlImg()
    {
        if ($this->request->isPost()) {
            $url_file = $this->request->param('url_file');

            $urlImgs = explode("\n", $url_file);

            if (!empty($urlImgs)) {
                try {
                    $filelist = [];
                
                    $url_path = Config::get('filesystem.disks.public.url');

                    foreach ($urlImgs as $urlImg) {
                        if ($urlImg) {
                            $savename = FileUtils::downloadUrlImg($urlImg);

                            $filelist[] =  $url_path . '/' . $savename;
                        }
                    }
                    return ReUtils::result($filelist);
                } catch (\think\exception\ValidateException $e) {
                    return ReUtils::error($e->getMessage());
                }
            } else {
                return ReUtils::error('图片地址不能为空');
            }
        }
    }

    /**
     * 附件上传
     */
    public function uploadMoive()
    {
        $file = $this->request->file('upload_movie');

        if ($file) {
            try {
                validate(
                    [
                        'file' => [
                            // 限制文件大小(单位b)，这里限制为20M
                            'fileSize' => 20 * 1024 * 1024,
                            // 限制文件后缀，多个后缀以英文逗号分割
                            'fileExt'  => 'mp4,flv,mpeg,avi'
                        ]
                    ],
                    [
                        'file.fileSize' => '文件太大',
                        'file.fileExt' => '不支持的文件后缀',
                    ]
                )->check(['file' => $file]);

                $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
                $url_path = Config::get('filesystem.disks.public.url');

                return ReUtils::result([
                    'filename' => $url_path . "/" . str_replace("\\", '/', $savename)
                ], 0, '上传成功');
            } catch (ValidateException $e) {
               return ReUtils::error($e->getMessage());
            }
        } else {
            return ReUtils::error('视频不能为空');
        }
    }

    /**
     * 附件上传
     */
    public function uploadFile()
    {
        $activepath = $this->request->has('activepath') ? $this->request->param('activepath') : '';

        $files = $this->request->file('upload_file');

        if ($files) {
            try {
                validate(
                    [
                        'file' => [
                            // 限制文件大小(单位b)，这里限制为10M
                            'fileSize' => 10 * 1024 * 1024,
                            // 限制文件后缀，多个后缀以英文逗号分割
                            'fileExt'  => 'jpg,png,gif,jpeg,webp,jfif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip'
                        ]
                    ],
                    [
                        'file.fileSize' => '文件太大',
                        'file.fileExt' => '不支持的文件后缀',
                    ]
                )->check(['file' => $files]);

                $uploadFiles = [];
                
                if (!is_array($files) && $files instanceof UploadedFile) {
                    $uploadFiles[] = $files;
                } else {
                    $uploadFiles = $files;
                }

                $url = Config::get('filesystem.disks.public.url');

                $filelist = [];

                foreach ($uploadFiles as $file) {
                    $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);                
                    
                    $filename = $file->getOriginalName();

                    $filelist[] = [
                        'url' => $url . '/' . $savename,
                        'filename' => $filename
                    ]; 
                }

               return ReUtils::result($filelist);
            } catch (ValidateException $e) {
                return ReUtils::error($e->getMessage());
            }
        } else {
            return ReUtils::error('图片不能为空');
        }
    }

    /**
     * ckeditor 富文本编辑器上传图片
     */
    public function ckeditorUploadImage()
    {
        if ($this->request->isPost()) {
            $file = $this->request->file('upload');
            if ($file) {
                try {
                    validate(
                        [
                            'file' => [
                                // 限制文件大小(单位b)，这里限制为4M
                                'fileSize' => 4 * 1024 * 1024,
                                // 限制文件后缀，多个后缀以英文逗号分割
                                'fileExt'  => 'jpg,png,gif,jpeg,webp,jfif'
                            ]
                        ],
                        [
                            'file.fileSize' => '文件太大',
                            'file.fileExt' => '不支持的文件后缀',
                        ]
                    )->check(['file' => $file]);

                    $source = str_replace("\\", '/', $this->app->getRootPath() . Env::get('watermark', 'public/static/images/watermark.png'));

                    if (!is_file($source)) {
                        $savename = \think\facade\Filesystem::disk('public')->putFile('/', $file);
                    } else {
                        $savename = $file->hashName();

                        $savepath = str_replace("\\", '/', Config::get('filesystem.disks.public.root') . DIRECTORY_SEPARATOR . $savename);

                        $dir = dirname($savepath);

                        if (!is_dir($dir)) {
                            mkdir($dir, 0755, true);
                        }
                        
                        $image = \think\Image::open($file);
                        
                        $image->water($source);

                        $image->save($savepath);
                        
                        $image = null;
                    }

                    return json([
                        'uploaded' => 1,
                        'fileName' => basename($savename),
                        'url' => Config::get('filesystem.disks.public.url') . '/' . $savename
                    ]);
                } catch (\think\exception\ValidateException $e) {
                    $this->error($e->getMessage());
                    return json([
                        'uploaded' => 1,
                        'error' =>  ['message' => $e->getMessage()]
                    ]);
                }
            } else {
                return json([
                    'uploaded' => 1,
                    'error' =>  ['message' => '图片不能为空']
                ]);
            }
        }
    }
}
